﻿using FreeSql;
using Microsoft.SemanticKernel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PluginSQLDemo.Plugins;

public sealed class FreeSqlPlugin
{
    private static readonly IFreeSql FreeSql = new FreeSqlBuilder()
        .UseConnectionString(global::FreeSql.DataType.Sqlite, "Data Source=./sk.db")
        .UseAutoSyncStructure(true)
        .Build();

    [KernelFunction("Execute")]
    [Description("用于执行不需要返回结果的SQL语句，返回是否执行成功，通常用于增删改操作。")]
    public async Task<bool> ExecuteAsync([Description("需要执行的Sqlite的Sql语句")] string sql)
    {
        var result = await FreeSql.Ado.ExecuteNonQueryAsync(sql);
        return result > 0;
    }

    [KernelFunction("Query")]
    [Description("用于执行需要返回结果的SQL语句，返回查询结果。")]
    public async Task<List<dynamic>> QueryAsync([Description("需要执行的Sqlite的Sql语句")]string sql)
    {
        var result = await FreeSql.Ado.QueryAsync<dynamic>(sql);
        return result;
    }

    [KernelFunction("QueryFirst")]
    [Description("用于执行需要返回结果的SQL语句，返回第一行查询结果。")]
    public async Task<dynamic> QueryFirstAsync([Description("需要执行的Sqlite的Sql语句")] string sql)
    {
        var result=await FreeSql.Ado.QuerySingleAsync<dynamic>(sql);
        return result;
    }

    [KernelFunction("QueryFirstOrDefault")]
    [ Description("用于执行需要返回结果的SQL语句，返回第一行查询结果，如果没有查询到结果则返回null。")]
    public async Task<dynamic> QueryFirstOrDefaultAsync([Description("需要执行的Sqlite的Sql语句")] string sql)
    {
        var result = await FreeSql.Ado.QuerySingleAsync<dynamic>(sql);
        return result;
    }
}
